package com.hospital.hms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.hospital.hms.dao.DoctorDao;
import com.hospital.hms.dao.MedicalDeptSubDoctorDao;
import com.hospital.hms.exception.GlobalException;
import com.hospital.hms.pojo.Doctors;
import com.hospital.hms.pojo.MedicalDeptSubDoctor;
import com.hospital.hms.service.DoctorService;
import com.hospital.hms.utils.PageUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class DoctorServiceImpl implements DoctorService {

    @Autowired
    DoctorDao doctorDao;

    @Autowired
    MedicalDeptSubDoctorDao medicalDeptSubDoctorDao;

//    分页查询
    @Override
    public PageUtils selectConditionByPage(Map param) {
        ArrayList<HashMap> list = null;
        long doctorCount = doctorDao.selectConditionByPageCount(param);
        if (doctorCount>0) {
            list = doctorDao.selectConditionByPage(param);
        }else {
            list = new ArrayList<>();
        }
        int page = MapUtil.getInt(param,"page");  //第几页
        int length = MapUtil.getInt(param,"length");  //每页的数据条数
        PageUtils pageUtils = new PageUtils(list,doctorCount,page,length);
        return pageUtils;
    }

//查询医生详细信息
    @Override
    public HashMap selectDoctorDetailById(int id) {
        HashMap hashMap = doctorDao.selectDoctorDetailById(id);
        //字符串=>JSON数组
        hashMap.replace("tag", JSONUtil.parseArray(MapUtil.getStr(hashMap,"tag")));

        String photo = (String) hashMap.get("photo");
        photo = photo.replace("http://113.45.145.70:9000", "https://xiaocheng.top:8444");

        hashMap.replace("photo", photo);

        return hashMap;
    }

//    添加医生
    @Override
    public void insert(Map param) {
        Doctors doctors = BeanUtil.toBean(param, Doctors.class);  //将doctor类转换为bean注解来进行添加
        doctorDao.insert(doctors);

//        根据uuid查询医生主键
        String uuid = doctors.getUuid();
        Integer doctorId = doctorDao.selectByUUID(uuid);

//        保存医生的诊室记录
        Integer subId = MapUtil.getInt(param, "subId");
        MedicalDeptSubDoctor medicalDeptSubDoctor = new MedicalDeptSubDoctor();
        medicalDeptSubDoctor.setDoctorId(doctorId);
        medicalDeptSubDoctor.setDeptSubId(subId);
        medicalDeptSubDoctorDao.insert(medicalDeptSubDoctor);   //添加医生诊室记录
    }

    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.access-key}")
    private String accessKey;
    @Value("${minio.secret-key}")
    private String secretKey;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Override
    @Transactional   //事务管理
    public void updatePicture(MultipartFile file,Integer doctorId) {
        String filename = "doctor-"+doctorId+".jpg";
        /*
         * 通过MinioClient操作Minio图片服务器，需要传递如下参数：
         *   1. 地址：endpoint
         *   2. 账号：accessKey
         *   3. 密码：secretKey
         *   4. bucket名：yiliao
         *
         * bucket：要根据实际上创建的来填写yiliao3
         * */
        try{
            String fileName = "doctor-"+doctorId+".jpg";
            MinioClient minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
                    .object("doctors/"+fileName)
                    .stream(file.getInputStream(),-1,5*1024*1024)
                    .contentType("image/jpeg").build()
            );

            //封装照片参数，更新数据库信息
            doctorDao.updatePicture(new HashMap(){{
                put("id",doctorId);
                put("photo", endpoint + bucketName + "/doctors/" + filename);

            }});
        }catch (Exception e){
            log.error("照片更新失败");
            e.printStackTrace();
            throw new GlobalException("照片更新失败");
        }
    }

    @Override
    public HashMap selectById(int id) {
        HashMap hashMap = doctorDao.selectById(id);
        if (hashMap != null) {
            String tag = (String) hashMap.get("tag");
            if (tag != null && !tag.isEmpty()){
                try{
                    JSONArray array = JSONUtil.parseArray(tag);
                    hashMap.put("tag",array);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return hashMap;
    }

    @Override
    @Transactional
    public void update(Map map) {
        doctorDao.update(map);
        //把map中的键换一个
        map = MapUtil.renameKey(map,"id","doctorId");
        medicalDeptSubDoctorDao.updateDoctorSubDept(map);
    }

    @Override
    public void deleteByIds(Integer[] ids) {
        doctorDao.deleteByIds(ids);
    }

    @Override
    public ArrayList<HashMap> selectDoctorsBySubId(int subId) {
        return doctorDao.selectDoctorsBySubId(subId);
    }

    /*
    * 移动端
    * */
//    @Override
//    public HashMap selectDoctorInfoById(int id) {
//        return doctorDao.selectDoctorInfoById(id);
//    }
}
